package com.jdkreader.concurrency.concurrent.delay;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

import static java.util.concurrent.TimeUnit.MICROSECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;

public class DelayedTask implements Runnable, Delayed {

    private static int counter = 0;
    private final int id = counter++;
    //任务延迟
    private final int delta;
    //任务延迟时间
    private final long trigger;
    //用于管理延时任务的队列
    protected static List<DelayedTask> sequence =
            new ArrayList<DelayedTask>();

    public DelayedTask(int delayMilliseconds){
        delta=delayMilliseconds;
        trigger=System.nanoTime() +
                NANOSECONDS.convert(delta,NANOSECONDS);
        sequence.add(this);
    }

    @Override
    public void run(){
        System.out.println(this+" ");
    }

    //任务延迟到期时间
    public long getDelay(TimeUnit unit){
        return unit.convert(delta-System.nanoTime(),NANOSECONDS);
    }

    public int compareTo(Delayed arg){
        DelayedTask that=(DelayedTask)arg;
        if(trigger < that.trigger) return -1;
        if(trigger > that.trigger) return 1;
        return 0;
    }

    public String toString(){
        return String.format("[%1$-4d]",delta)+
                "Task "+id;
    }

    public String summary(){
        return "("+id+":"+delta+")";
    }


}
